package com.raul.AgendaAndroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.raul.AgendaAndroid.beans.Agenda;
import com.raul.AgendaAndroid.util.URLKeys;

public class NewContactActivity extends Activity {

	private static final int CONSTANTE_NOMBRE = 1;
	private static final int CONSTANTE_APELLIDO = 2;
	private static final int CONSTANTE_CALLE = 3;
	private static final int CONSTANTE_CP = 4;
	private static final int CONSTANTE_LOCALIDAD = 5;
	private static final int CONSTANTE_PROVINCIA = 6;
	private static final int CONSTANTE_FIJO = 7;
	private static final int CONSTANTE_MOVIL = 8;
	private static final int CONSTANTE_ANOTACIONES = 9;
	private static final int CONSTANTE_EMAIL = 10;
	// private static final int TIMEOUT_MILLISEC = 3000;
	private Agenda agenda = new Agenda();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_contact);

		Button btNuevoContacto = (Button) findViewById(R.id.bt_save);
		btNuevoContacto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!validate()) {
					Toast.makeText(getBaseContext(), "Enter some data!",
							Toast.LENGTH_LONG).show();
				}
				new HttpAsyncTask().execute();
				finishActivity(0);
			}
		});
	}

	private boolean validate() {
		return true;
	}

	private String POST(String url) {
		// Parsear los valores introducidos por el usuario en la
		// pantalla.

		agenda.setNombre(getValues(CONSTANTE_NOMBRE));
		agenda.setApellido(getValues(CONSTANTE_APELLIDO));
		agenda.setCalle(getValues(CONSTANTE_CALLE));
		agenda.setCp(getValues(CONSTANTE_CP));
		agenda.setLocalidad(getValues(CONSTANTE_LOCALIDAD));
		agenda.setProvincia(getValues(CONSTANTE_PROVINCIA));
		agenda.setFijo(getValues(CONSTANTE_FIJO));
		agenda.setMovil(getValues(CONSTANTE_MOVIL));
		agenda.setProvincia(getValues(CONSTANTE_ANOTACIONES));
		agenda.setEmail(getValues(CONSTANTE_EMAIL));

		// Enviar el JSON a la pagina para guardar los datos en la base
		// de datos
		JSONObject jsonObject = null;
		String json = "";
		InputStream inputStream = null;
		String result = "";
		try {

			// 1. create HttpClient
			HttpClient httpclient = new DefaultHttpClient();

			// 2. make POST request to the given URL
			HttpPost httpPost = new HttpPost();

			// 3. build jsonObject
			jsonObject = parseJSON(agenda);

			// 4. convert JSONObject to JSON to String
			json = jsonObject.toString();

			// 5. set json to StringEntity
			StringEntity se = new StringEntity(json);

			// 6. set httpPost Entity
			httpPost.setEntity(se);

			// 7. Set some headers to inform server about the type of
			// the content
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-type", "application/json");

			// 8. Execute POST request to the given URL
			HttpResponse httpResponse = httpclient.execute(httpPost);

			// 9. receive response as inputStream
			inputStream = httpResponse.getEntity().getContent();

			// 10. convert inputstream to string
			if (inputStream != null) {
				result = convertInputStreamToString(inputStream);
			} else {
				result = "Did not work!";
			}

			return result;

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			// Utilidades.alertas(e.getMessage(),
			// //NewContactActivity.class);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			// Utilidades.alertas(e.getMessage(),
			// //ewContactActivity.class);
		} catch (IOException e) {
			e.printStackTrace();
			// Utilidades.alertas(e.getMessage(),
			// //NewContactActivity.class);

		} catch (JSONException e) {
			e.printStackTrace();
			// Utilidades.alertas(e.getMessage(),
			// NewContactActivity.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private class HttpAsyncTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {

			return POST(URLKeys.INSERT);
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG)
					.show();
		}
	}

	private static String convertInputStreamToString(InputStream inputStream)
			throws IOException {
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line = "";
		String result = "";
		while ((line = bufferedReader.readLine()) != null)
			result += line;

		inputStream.close();
		return result;

	}

	/**
	 * Obtiene los valores introducidos en los controles de la pantalla.
	 * 
	 * @param numControl
	 *            : Numero de control para parsear el valor.
	 * @return : Devuelve el contenido de los controles de la interfaz.
	 */
	private String getValues(int numControl) {
		TextView control = null;
		String res;

		switch (numControl) {
		case CONSTANTE_NOMBRE:
			control = (TextView) findViewById(R.id.tx_nombre);
			break;
		case CONSTANTE_APELLIDO:
			control = (TextView) findViewById(R.id.tx_apellido);
			break;
		case CONSTANTE_CALLE:
			control = (TextView) findViewById(R.id.tx_calle);
			break;
		case CONSTANTE_CP:
			control = (TextView) findViewById(R.id.tx_cp);
			break;
		case CONSTANTE_LOCALIDAD:
			control = (TextView) findViewById(R.id.tx_localidad);
			break;
		case CONSTANTE_PROVINCIA:
			control = (TextView) findViewById(R.id.tx_provincia);
			break;
		case CONSTANTE_FIJO:
			control = (TextView) findViewById(R.id.tx_fijo);
			break;
		case CONSTANTE_MOVIL:
			control = (TextView) findViewById(R.id.tx_movil);
			break;
		case CONSTANTE_ANOTACIONES:
			control = (TextView) findViewById(R.id.tx_anotaciones);
			break;
		case CONSTANTE_EMAIL:
			control = (TextView) findViewById(R.id.tx_email);
			break;
		default:
			break;
		}

		res = "";
		if (control.getText().toString() != "") {
			res = control.getText().toString();
		}
		return res;
	}

	private JSONObject parseJSON(Agenda agenda) throws JSONException {

		JSONObject json = new JSONObject();

		json.put("nombre", agenda.getNombre());
		json.put("apellido", agenda.getApellido());
		json.put("calle", agenda.getCalle());
		json.put("cp", agenda.getCp());
		json.put("localidad", agenda.getLocalidad());
		json.put("provincia", agenda.getProvincia());
		json.put("fijo", agenda.getFijo());
		json.put("movil", agenda.getMovil());
		json.put("anotaciones", agenda.getAnotaciones());
		json.put("email", agenda.getEmail());
		return json;
	}

}
